<template>
  <div class="cardRevenue">
    <x-header class="header" :left-options="{showBack: showHeaderBack,preventGoBack:true}" @on-click-back="goToPage" ref="header">办卡/充值收入</x-header>
    <div class="topHolder"></div>
    <card class="gridDisplay">
      <div class="card-padding" slot="content" style="padding-top: 0;">
        <div class="filterArea dateFilter" ref="filterArea">
          <group-title style="text-align: center;">当前显示日期：{{choosenDate}}<br/></group-title>
          <x-button :show-loading="loadingStatus" :disabled="loadingStatus" @click.native="changeDate(1)" class="inlineBtn">今日</x-button>
          <x-button :show-loading="loadingStatus" :disabled="loadingStatus" @click.native="changeDate(2)" class="inlineBtn">昨日</x-button>
          <a v-if="loadingStatus" class="datePicker"><i class="iconfont icon-rilicalendar107"></i></a>
          <datetime v-else v-model="choosenDate" :start-date="startDate" :end-date="endDate" @on-confirm="changeDate(0)" class="datePicker">
            <i class="iconfont icon-rilicalendar107"></i>
          </datetime>
        </div>
        <h2 class="title">
          ¥ <span v-text="formatCurrency(revenueInfo.total)">0</span>元<br/>
          <small>总办卡/充值收入：</small>
        </h2>
        <grid :cols="2" style="text-align: center;">
          <grid-item label="办卡收入：">
            <span class="data">¥ <span v-text="formatCurrency(revenueInfo.applyRevenue)">0</span>元</span>
          </grid-item>
          <grid-item label="充值收入：">
            <span class="data">¥ <span v-text="formatCurrency(revenueInfo.chargeRevenue)">0</span>元</span>
          </grid-item>
          <grid-item label="办卡次数：">
            <span class="data"><span v-text="revenueInfo.applyNum">0</span></span>
          </grid-item>
          <grid-item label="充值次数：">
            <span class="data"><span v-text="revenueInfo.chargeNum">0</span></span>
          </grid-item>
        </grid>
      </div>
    </card>
    <group title="按卡类分充值收入明细（双指操作放大缩小，按住左右滑动，长按显示标签）：">
      <canvas height="260" class="noselect" ref="multiChart"></canvas>
      <div style="height: 30px;"></div>
    </group>
    <card>
      <div class="card-padding" slot="content">
        <div class="filterArea">
          <div class="filterItem">开卡类型明细：<x-button @click.native="showSortType = true" type="default" v-html="sortTypeText" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button>&nbsp</div>
        </div>
        <popup-picker @on-hide="popupPickerFunc" :show.sync="showSortType" :show-cell="false" :data="sortType" :columns="1" v-model="choosenSortType" ref="sortType" class="btn_popup-picker"></popup-picker>
      </div>
    </card>
    <group class="tableDisplay">
      <x-table :cell-bordered="false">
        <thead>
        <tr style="background-color: #F7F7F7">
          <th width="43%">卡类型</th>
          <th width="22%">开卡数量</th>
          <th width="35%">开卡金额</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item,index) in revenueInfo.typeDetail" :key="index">
          <td v-text="item.cardName"></td>
          <td v-text="item.number"></td>
          <td v-text="'¥ ' + formatCurrency(item.total) + '元'"></td>
        </tr>
        <tr v-if="JSON.stringify(revenueInfo) != '{}' && revenueInfo.typeDetail.length <= 0">
          <td colspan="3">
            <div class="listNoItem">暂无开卡类型明细</div>
          </td>
        </tr>
        </tbody>
      </x-table>
    </group>
    <group title="按付款方式分办卡/充值收入明细：">
      <canvas height="260" class="noselect" ref="pieChart"></canvas>
      <div style="height: 30px;"></div>
    </group>
  </div>
</template>

<script>
  import F2 from '@antv/f2/build/f2-all.js'
  import {XButton, Card, Grid, GridItem, Group, Datetime, PopupPicker, GroupTitle, XTable, numberComma, dateFormat } from 'vux'
  import {getCardRevenue} from "../../api";
  import {message,toDecimal2} from "../../common/util";

  export default {
    name:'cardRevenue',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:true,
        choosenDate:dateFormat(new Date(), 'YYYY-MM-DD'),
        startDate:'2019-01-01',
        endDate:dateFormat(new Date(), 'YYYY-MM-DD'),
        revenueInfo:{},
        multiChartData:[],
        multiChartData_name:[],
        multiChart:{},
        pieChartData:[],
        pieChart:{},
        pieChartHeight:250,
        showSortType:false,
        sortType:[{name:'按数量排行',value:'sortByNumber'},{name:'按金额排行',value:'sortByTotal'}],
        sortTypeText:'',
        choosenSortType:['sortByTotal']
      }
    },
    components:{
      XButton,
      Card,
      Grid,
      GridItem,
      Group,
      Datetime,
      PopupPicker,
      GroupTitle,
      XTable
    },
    computed:{
    },
    methods:{
      goToPage(){
        this.$router.push({path:'/'})
      },
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      changeDate(value){
        console.log(value)
        switch (value) {
          case 1:this.choosenDate = dateFormat(new Date(), 'YYYY-MM-DD');break;
          case 2:this.choosenDate = dateFormat(new Date().setDate(new Date().getDate()-1), 'YYYY-MM-DD');break;
          default: break;
        }
        console.log(this.choosenDate)
        this.changeChartData()
      },
      refreshPage(params){
        this.loadingStatus = true
        this.multiChartData = []
        this.pieChartData = []
        this.pieChartHeight = 250
        getCardRevenue(this.choosenDate).then((res)=>{
          if(res.status == 'success'){
            this.revenueInfo = res.data
            this.multiChartData = JSON.parse(JSON.stringify(this.revenueInfo.typeDetail))
            this.pieChartHeight += this.revenueInfo.payMethodDetail.length * 20
            this.revenueInfo.payMethodDetail.forEach(item =>{
              this.pieChartData.push({amount: item.value,ratio: item.value/this.revenueInfo.total,memo: item.name,const: 'const'})
            })
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getCardRevenue error info:', res.msg)
          }
          if(params && params.callback && typeof params.callback == 'function')params.callback(res.status)
        }).catch((err)=>{console.log('getCardRevenue catch info:',err)})
      },
      initMultiChart(){
        this.multiChartData_name = []
        const windowWidth = window.innerWidth
        /*const windowHeight = window.innerHeight
        let itemNum = windowWidth < windowHeight?5:10
        for(let i = this.multiChartData.length - 1; i >= this.multiChartData.length - itemNum; i--){
          this.multiChartData_name.push(this.multiChartData[i].cardName)
        }
        this.multiChartData_name.reverse()*/
        this.multiChart = new F2.Chart({
          id: this.$refs.multiChart,
          width: windowWidth,
          pixelRatio: window.devicePixelRatio,
          height: 320,
          padding: ['auto', 'auto', 110, 'auto']
        });
        this.multiChart.source(this.multiChartData, {
          total: {tickCount: 5},
          number: {tickCount: 5}/*,
          cardName: {
            values: this.multiChartData_name
          }*/
        })
        this.multiChart.axis('cardName', {
          label: {
            rotate: Math.PI / 3,
            textAlign: 'start',
            textBaseline: 'middle'
          }
        });
        this.multiChart.tooltip({
          showItemMarker: false,
          onShow: function onShow(ev) {
            var items = ev.items;
            items[0].name = null;
            items[1].name = '金额';
            items[2].name = '数量';
            items[1].value = '¥ ' + items[0].value + '元';
            items[0].value = items[0].title;
          }
        })
        this.multiChart.interval().position('cardName*total').color('#FACC14');
        this.multiChart.line().position('cardName*number').color('#000');
        this.multiChart.point().position('cardName*number').size(3).style({
          fill: '#000',
          stroke: '#fff',
          lineWidth: 1
        });
        // 定义进度条
        this.multiChart.scrollBar({
          mode: 'x',
          xStyle: {
            backgroundColor: '#e8e8e8',
            fillerColor: '#808080',
            offsetY: -2
          }
        });
        this.multiChart.interaction('pinch').interaction('pan');
        this.multiChart.render();
      },
      changeChartData(){
        this.refreshPage({callback:(status)=>{
            if(status == 'success') this.reInitChart()
            this.loadingStatus = false
          }})
      },
      initPieChart(){
        const windowWidth = window.innerWidth
        const windowHeight = window.innerHeight
        this.pieChart = new F2.Chart({
          id: this.$refs.pieChart,
          width: windowWidth,
          height: this.pieChartHeight ? this.pieChartHeight : (windowWidth > windowHeight ? (windowHeight - 54) : windowWidth * 0.707),
          pixelRatio: window.devicePixelRatio
        });
        this.pieChart.source(this.pieChartData)
        this.pieChart.coord('polar', {
          transposed: true,
          innerRadius: 0.4,
          radius: 0.75
        });
        this.pieChart.axis(false);
        this.pieChart.legend({
          position: 'bottom',
          align: 'center',
          itemMarginBottom: 20
        });
        this.pieChart.tooltip(false);
        this.pieChart.guide().html({
          position: ['50%', '50%'],
          html: '<div style="width: 80px;height: 20px;text-align: center;line-height: 20px;font-size: 0.9rem" id="textContent">收入明细</div>'
        });
        // 配置文本饼图
        this.pieChart.pieLabel({
          sidePadding: 15,
          label1: function label1(data) {
            return {
              text: data.memo,
              fill: '#808080'
            };
          },
          label2: function label2(data) {
            return {
              fill: '#000000',
              text: '¥' + data.amount + '元'
            };
          }
        });
        this.pieChart.interval().position('const*ratio').color('memo', ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0', '#3436C7', '#223273']).adjust('stack');
        this.pieChart.render();
        // 绘制内阴影
        var frontPlot = this.pieChart.get('frontPlot');
        var coord = this.pieChart.get('coord'); // 获取坐标系对象
        frontPlot.addShape('sector', {
          attrs: {
            x: coord.center.x,
            y: coord.center.y,
            r: coord.circleRadius * coord.innerRadius * 1.2, // 全半径
            r0: coord.circleRadius * coord.innerRadius,
            fill: '#000',
            opacity: 0.15
          }
        });
        this.pieChart.get('canvas').draw();
      },
      reInitChart(){
        this.multiChart.destroy()
        this.pieChart.destroy()
        this.initMultiChart()
        this.initPieChart()
      },
      sortTable(){
        if(this.choosenSortType == 'sortByNumber'){
          this.revenueInfo.typeDetail.sort(function(item1,item2){
            if(item1.number > item2.number){
              return -1;
            }else if(item1.number < item2.number){
              return 1;
            }
            return 0;
          })
          console.log(this.multiChartData)
        }else if(this.choosenSortType == 'sortByTotal'){
          this.revenueInfo.typeDetail.sort(function(item1,item2){
            if(item1.total > item2.total){
              return -1;
            }else if(item1.total < item2.total){
              return 1;
            }
            return 0;
          })
          console.log(this.multiChartData)
        }
      },
      popupPickerFunc(closeType){
        if(closeType){
          this.changeSortTypeText()
          this.sortTable()
        }
      },
      changeSortTypeText(){
        this.sortTypeText = this.$refs.sortType&&this.$refs.sortType.getNameValues().replace(/ /g,' / ')+'<i class=\'iconfont icon-xiangxia2\'></i>'
      }
    },
    mounted(){
      this.refreshPage({callback:(status)=>{
          if(status == 'success'){
            this.initMultiChart()
            this.initPieChart()
            this.sortTable()
            window.addEventListener('resize', this.reInitChart)
          }
          setTimeout(()=>{this.changeSortTypeText()},200)
          this.loadingStatus = false
          this.$store.commit('updateLoadingStatus',{isLoading:false})
        }})
    },
    beforeDestroy () {
      window.removeEventListener('resize', this.reInitChart)
      this.multiChart.destroy()
      this.pieChart.destroy()
    }
  }
</script>

<style lang="scss">
  .cardRevenue{
    .gridDisplay{
      .filterArea{
        &.dateFilter{
          margin-bottom: 0.5rem;
          .datePicker{
            float: right;padding: 0;
            &.weui-cell:before{border-top: none;}
            i{font-size: 2rem;color:#535353;}
          }
        }
        .filterItem{margin-top: 0.5rem;}
      }
      h2.title{
        line-height: 1.8rem;color: #636363;font-size:2rem;text-align: center;margin: 1rem 0;
        small{font-size:1rem;color: #999999;}
      }
      .data{display: inline-block;height:1.5rem;}
    }
    .tableDisplay{
      .vux-no-group-title{margin-top: 0;}
    }
    .noselect {
      -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none; /* Safari */
      -khtml-user-select: none; /* Konqueror HTML */
      -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* Internet Explorer/Edge */
      user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
    }
  }
</style>
